package us.versus.them.kitkattoe;

import flash.display.Graphics;
import flash.display.DisplayObject;
import flash.display.MovieClip;
import flash.geom.Point;
import flash.media.Sound;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;

class StartGame extends Base {
	var app:App;
	var cats:Array< DisplayObject >;
	var meow:Sound;
	var velocity:Array< Point >;

	public function new( app, cats:Array< DisplayObject >, meow:Sound ) {
		super();
		this.app = app;
		this.cats = cats;
		this.meow = meow;
		this.velocity = new Array< Point >();
		addChild( Base.displayObjectForName( 'hi' ) );
		for ( cat in cats ) { 
			cat.x = Math.random() * Base.w;
			cat.y = Math.random() * Base.h;
			this.velocity.push( new Point() );
			addChild( cat );
		}
	}

	public override function init() {
		this.addEventListeners();
	}

	public override function mouse_down( mouseEvent : MouseEvent ) {
		this.app.newGame();
	}

	public override function mouse_up( mouseEvent : MouseEvent ) {
		this.app.newGame();
	}

	public override function key_down( keyboardEvent : KeyboardEvent ) {
		this.app.newGame();
	}

	override public function draw( g:Graphics ) {
		var i = 0;
		for ( cat in cats ) { 
			var pt = this.velocity[ i++ ];
			cat.x += pt.x;
			cat.y += pt.y;
			pt.x += this.less( cat.x, Base.w );
			pt.y += this.less( cat.y, Base.h );
			if ( cat.x < 0 ) pt.x++;
			if ( cat.y < 0 ) pt.y++;
			if ( cat.x > Base.w ) pt.x--;
			if ( cat.y > Base.h ) pt.y--;


		}

		for ( i in 0 ... cats.length ) {
			var pt = this.velocity[ i];
			var cat = this.cats[ i ];

			for ( j in  i + 1 ... cats.length ) {
				var kat = cats[ j ];
				if ( cat.hitTestObject( kat ) ) {
					var tp = this.velocity[ j ];
					var ox = ( cat.x - kat.x ) / 12;
					var oy = ( cat.y - kat.y ) / 12;
					pt.x += ox;
					pt.y += oy;
					tp.x -= ox;
					tp.y -= oy;
					//meow.play(); /* this is going to be terrible... */
				}
			}
		}

		var max = 10;
		for ( pt in this.velocity ) {
			if ( pt.x < -max ) pt.x = -max;
			if ( pt.x >  max ) pt.x =  max;
			if ( pt.y < -max ) pt.y = -max;
			if ( pt.y >  max ) pt.y =  max;
		}
	}

	public function less( x, v ) {
		return if ( x < v / 4 ) 1 else -1;
	}
}
